
//注册静态资源
Ccay.Component = {};

/**
 * @description  载入差异日志 
 * @param [JQDom] panel 目标对象或对象JQID
 * @param [String] module 模块名称
 * @param [String] objectId 目标对象ID
 */
Ccay.Component.difLog = function(panel,module,objectId)
{
	$(panel).ccayLoad("ccay/js/common/component/difLog/difLogContainer.html",function(){
		$("#view_logs_").click(function(){
			Ccay.Component.DifLog.showHiddView(module,objectId);
		});
	});
}


/**
 * 打开上传对话框
 */
Ccay.Component.openUploadDialog = function(title,param,width,height){
	if($("div[module='Ccay.Upload.Dialog']").length){
		return;//若是有初始对象，就直接返回
	}
	Ccay.Page.register("Ccay.Upload.Dialog","ccay/upload/support/dialog.html");
	//保存以避免会话重建丢失
	Ccay.Component.uploadDialogParam = param; 
	Ccay.Common.openPage(title,"Ccay.Upload.Dialog",{
		height:height || 290,width:width || 560,	
		fnBeforeClose:function(){ 
			if(Ccay.Upload.Dialog && Ccay.Upload.Dialog.exit){
				try{Ccay.Upload.Dialog.exit();}catch(e){}
			}
		},
		buttons:[{
			type:"imgBtn",
      	    icon:"cancel",
      	    cls:"ccay-icon",
			text:"ccay.common.label.close",
			onClick:function(){
				if(Ccay.Upload.Dialog && Ccay.Upload.Dialog.closeDialog){
					Ccay.Core.log("Before close upload dialog");
					try{Ccay.Upload.Dialog.closeDialog();}catch(e){}
				}
			}}]
	},function(){
		Ccay.Core.log("Before init upload dialog.");
		Ccay.Upload.Dialog.init(Ccay.Component.uploadDialogParam);
		Ccay.Component.uploadDialogParam = null;
	});
};

/**
 * 打开上传对话框
 */
Ccay.Component.customUpload = function(param){
	Ccay.Page.register("Ccay.Upload.Custom","ccay/upload/support/custom.html");
	Ccay.Core.log("Before init upload custom.");
	var div = $("#customUpdalodJSdiv");
	if(div.length == 0){
		window.uploadLoadBack = $.Callbacks();
		div = $("<div id='customUpdalodJSdiv' style='margin:0px;display:none'></div>").appendTo(document.body);
		div.ccayLoad('ccay/upload/support/custom.html',function(){
			Ccay.Upload.Custom.init(param);
			window.uploadLoadBack.fire();
		});
	}else{
		if(!Ccay.Upload || !Ccay.Upload.Custom){
			window.uploadLoadBack.add(function(){
				Ccay.Upload.Custom.init(param);
			})
		}else{
			window.uploadLoadBack.clear()
			Ccay.Upload.Custom.init(param);
		}
	}
};
Ccay.Component.Excel={};
/**
 * Excel 导入文件上传成功时的提示回调函数
 */
Ccay.Component.Excel.uploadCallback = function(){
	Ccay.UI.showMessage("ccay.common.message.importUploadSucess","success",null,false,false);
}
Ccay.Component.Excel.uploadCallback_topBox = function(){
	Ccay.UI.topBox(
	{
		css:"callback-topbox",
		content:"ccay.common.message.importUploadSucess.title",
		character:"ccay.common.message.importUploadSucess.topBox",
		forwardUrl:"ccay/async/task/listImport.html",//指定跳转url，可选
		type:"big_com",//可选值 : big_com    big_sim
		noTitle:true //是否显示title
	});
}
/**
 * Excel 导出成功提交后提示回调函数
 */
Ccay.Component.Excel.exportCallback = function(){
	Ccay.UI.showMessage("ccay.common.message.exportSucess","success",null,false,false);
}
Ccay.Component.Excel.exportCallback_topBox = function(){
	Ccay.UI.topBox(
	{
		css:"callback-topbox",
		content:"ccay.common.message.exportSucess.title",
		character:"ccay.common.message.exportSucess.topBox",
		forwardUrl:"ccay/async/task/listExport.html",//指定跳转url，可选
		type:"big_com",//可选值 : big_com    big_sim
		noTitle:true //是否显示title
	});
}


/**@description 调用通用弹出框方法
 * @param {Object} popupBean  通用参数框，参数定义： popupBean={defaultSearch:true,servicePath:"",uniqueKey:"roleName",callback:"",selectedItems:"",columns:null};
 *  popupBean.servicePath {String}  对应rest service的服务路径，根据该路径，调用其通用查询服务
 *  popupBean.selectedItems{String[]} 多选弹出框使用, [2,3,5,7] or ["china","usa","japan"]
 *  popupBean.columns     {Object[]}  显示列头定义，如：[{label:"第一列",name:"roleId"}{label:"第二列",name:"roleName"}]
 *  popupBean.uniqueKey   {string} 查询数据中的一个唯一键属性名，require。
 *  popupBean.callback {function}  弹出框选择确认后的回调函数
 *  popupBean.selectPath
 * @param {String} title   弹出框标题
 * @param {boolean} isMultiSelect   是否多选
 * @param {number} width   弹出框宽度 可不传
 * @param {number} height  弹出框高度 可不传
 */
Ccay.Component.popup=function(popupBean,title,isMultiSelect,width,height){
		//debugger;
		if(isMultiSelect){
			width = width || 920;
			minHeight = height|| 470
		}else{  
			width = width|| 550;
			minHeight= height|| 460
		}
		var popupDialog,popupModel,resKey= isMultiSelect? "Ccay.Component.MultiPopup":"Ccay.Component.SinglePopup";
		// 修复弹出框按Enter按钮的时候出现多个弹出框 
		if( Ccay.Module.modules.data[resKey]){
			return ;
		}
		//获得单选多选html模板资源
		if(popupBean.resKey && popupBean.resPath){
			//自定义弹出框页面
			resKey=popupBean.resKey;
			Ccay.Page.register(popupBean.resKey,popupBean.resPath); 
		}else{
			//使用默认弹出框页面
			var str = popupBean.igrid ? "i" : ""; 
			Ccay.Page.register("Ccay.Component.SinglePopup","ccay/js/common/component/popup/{0}singlePopup.html".formatText(str)); 
			Ccay.Page.register("Ccay.Component.MultiPopup","ccay/js/common/component/popup/{0}multiPopup.html".formatText(str));	
		}
		popupModel=Ccay.Core.Namespace.register(resKey);
		
		var options={"minHeight":minHeight,maxHeight : minHeight + 40, "width":width,fnBeforeClose:popupBean.beforeClose,callback:function(){
			var mudule=Ccay.Core.Namespace.register(resKey);
			mudule.context=popupModel.context;
			mudule.init(popupBean)
		},
		cancelClick: true,
		buttons:[{text:$i18n("ccay.common.button.clearselect"),onClick:function(){
			popupBean.fnClear();
		}}]};
		
		//提供自定义dialog属性
		options = $.extend( options,popupBean.dialogOp);
		
		if(popupBean.simpleMode || isMultiSelect || popupBean.resKey){
			options.okClick = function(){
				var mudule=Ccay.Core.Namespace.register(resKey);
				mudule.context=popupModel.context;
				mudule.onOk(); 
			}
		}
		if(typeof popupBean.fnClear!="function"){//如果popupBean中实现了fnClear参数，则为弹出框添加一个清空的按钮
			delete options.buttons;
		}
		if(popupBean.buttons===null){//如果popupBean 中buttons参数为null，则去掉默认的按钮与shijian
			delete options.okClick;
		}
		popupDialog=Ccay.UI.dialog(resKey,title,options);
		
		if(popupBean.needReturn){
			return popupDialog;
		}
};




/**
 * 弹出树接口
 * @param {String} title
 * @param {String} dataOrUrl
 * @param {Object} treeSetting
 * @param {function} selectCallback
 * @param {boolean} isMulti
 * @param {number} width
 * @param {number} height
 * @param {object} dialogOp 关于dialog的参数设置
 * @return {Jqdom} tree dom
 */
Ccay.Component.popupTree = function(title,dataOrUrl,treeSetting,selectCallback,width,height,dialogOp) {
	treeSetting=treeSetting || {};
	var miniHeight=20;
	if(treeSetting.filter!==false){
		treeSetting.filter=true;
		miniHeight=50;
	}
		
	var dialog,treeId="popTree"+parseInt(Math.random()*100000);
	 width = width || 300; 
	 height = height || 400;
	var options={width:width,height:height,content:"<ul id='"+treeId+"' style='width:"+width+"px;height:"+(height-miniHeight)+"px;overflow: auto;'></ul>",cancelClick:true,okClick:function(){
		var tree=$("#"+treeId).getCcayTreeManager();
		if(selectCallback && selectCallback(tree.getCheckedNodes() || [])!==false){
			dialog.close();
		}
	}};
	if(!treeSetting.checkType || treeSetting.checkType=="single"){
		treeSetting.checkType="single";
	}
    dialog=Ccay.UI.dialog("",title,$.extend(options,dialogOp)); 
    return $("#"+treeId).ccayTree(dataOrUrl,treeSetting,function(){
    		treeSetting.callback && treeSetting.callback(); 
    });
}

/**
 * 会话重建组件
 */
Ccay.Component.Session={};

/**
 * 打开会话重建对话框
 */
Ccay.Component.Session.openRebuildDialog = function(fnCallback,callbackParameter){
	if(Ccay.Component.Session.isOpen){		
		Ccay.Core.log("Rebuild dialog already opened.");
		return ;
	}	
	Ccay.Component.Session.isOpen = true;
	 
	//保存回调的函数和参数
	Ccay.Component.Session.fnCallback = fnCallback;
	Ccay.Component.Session.callbackParameter = callbackParameter;
	
	Ccay.Component.Session.dialog = Ccay.UI.dialog("login.html","ccay.common.message.sessionrebuild",{width:625,height:450,load:false,
		fnBeforeClose:function(){
			delete Ccay.Component.Session.dialog;		
			delete Ccay.Component.Session.isOpen;
		}
	});
	
	$('.loading,#loading_msg').hide();
}
 
/**
 * 会话重建完成的回调函数
 */
Ccay.Component.Session.rebuiltCallback = function(userAccount){
	//关闭重建对话框
	Ccay.Component.Session.dialog.close();
	
	if(workspaceVO.user == null || userAccount != workspaceVO.user.name){
		Ccay.UI.topBox("ccay.common.message.userChanged");
		//用户发生了切换，重新装载首页
		setTimeout(function(){$(window.document.body).loading()},2000);		
		setTimeout(function(){window.location.href = workspaceVO.contextPath},3000);		
		return;
	}
	
	if(typeof Ccay.Component.Session.fnCallback=="function"){
		//执行回调函数
		Ccay.Component.Session.fnCallback(Ccay.Component.Session.callbackParameter);
		//销毁资源
		delete Ccay.Component.Session.fnCallback;
		delete Ccay.Component.Session.callbackParameter;
	}
	//显示完成信息
	Ccay.UI.topBox("ccay.common.message.sessionRebuildDone");
}

/**
 * 新窗口显示错误信息。
 */
Ccay.Component.showHandleError = function(dom){
	var msg = $(dom).data("msg");
	var blank = window.open("about:blank");
	blank.document.write((msg+" ").encode());
};

/**
 * 
 * @param {} responseText 响应文本
 * @param {} textStatus 一般没啥用
 * @param {} xhr XmlHttpRequest的对象
 * @param {} fnCallback 回调函数，有时候也用来存储当前Form
 * @param {} callbackParameter 回调函数需要的参数
 */
Ccay.Component.handleError = function(responseText, textStatus, xhr, fnCallback, callbackParameter){
	//debugger;
	//关闭主Loading框
	Ccay.UI.loadingClose();
	//Ccay.Core.log("Response Error Got:" + responseText +" Code:" +xhr.status);
	if(xhr.status == 403){		
		Ccay.Core.log("Before open session rebuild dialog.");
		//打开会话重建对话框
		Ccay.Component.Session.openRebuildDialog(fnCallback,callbackParameter);
	}else if(xhr.status == 401){
		Ccay.Component.handleNoPermissionEror(responseText);
	}else if(xhr.status == 404){
		Ccay.UI.showMessage("ccay.common.message.notFoundResouceError","error");
	}else if( (typeof responseText == "string") && responseText.substring(0,1) == "{" ){
		//返回JSON字符串，则解析之
		var fault =  Ccay.DataHelper.toJson(responseText);
		if(fault.code === "ccay.validator.00010001"){
			Ccay.Component.handleValidationError(fault,  fnCallback, callbackParameter);
		}else{
		 	// begin modify by zwx304259 sp20 运行时异常获取堆栈信息,抛出自定义没有堆栈信息
			if(fault.stackTrace){
				var ms = fault.stackTrace;
				ms = ms.replaceAll("\n","");
				ms = ms.replaceAll("\r","");
				ms=ms.replace(/\'/g,"");//替换半角单引号为全角单引号
				ms=ms.replace(/\"/g,"");//替换半角双引号为全角双引号
				ms=ms.replace(/\</g,"");
				ms=ms.replace(/\>/g,"");
				
				fault.message+="<br/><div class='ccay-form-input'><span id='detailLog' class='ccay-button' ccayPermission='Service$Logs.Search$SearchLogInfo' onclick='Ccay.Component.showHandleError(this)'><a class='ccay-icon execute'></a>Detail Log</span></div>";
			}
			// end modify by zwx304259
			
			if(fault.code == "unknown"){
				var i18nKey="ccay.common.message.systemExceptionError";
				var i18nMessage = $i18n(i18nKey);
				if(i18nMessage !== i18nKey){
					Ccay.UI.showMessage(i18nMessage,"error");
				}
				else{
					// begin modify by zwx304259 sp20 运行时异常获取堆栈信息,抛出自定义没有堆栈信息走else提示信息
					if(fault.stackTrace){
						Ccay.UI.showMessage(fault.message,"error",null,null,false,null);
						$("#detailLog").ccayHasPermission();
						$("#detailLog").length && $("#detailLog").data("msg", ms);
					}
					else
					{
						Ccay.UI.showMessage(fault.message,"error");
					}
					// end modify by zwx304259
				}
			}else{
				// begin modify by zwx304259 sp20 运行时异常获取堆栈信息,抛出自定义没有堆栈信息走else提示信息
				if(fault.stackTrace){
					Ccay.UI.showMessage(fault.message,"error",null,null,false,null);
					$("#detailLog").ccayHasPermission();
				}
				else
				{
					Ccay.UI.showMessage(fault.message,"error");
				}
				// end modify by zwx304259 sp20
			}
			 
		}
	}else{
		Ccay.Core.log(responseText);
		//if(responseText.)
		Ccay.UI.showMessage("ccay.common.message.unknownError","error");
	}
};

/**
 * 处理无权错误
 * @param {} responseText 响应文本
 */
Ccay.Component.handleNoPermissionEror =function(responseText){
	//debugger;
	var fault =  Ccay.DataHelper.toJson(responseText);//fault.entity关联到对应的权限点
	alert("您没有权限"+fault.entity);
	return ;
	if(fault && fault.entity){
		var permItems = fault.entity.split("$");
		if(permItems.length == 4 && permItems[0] != "null" && permItems[0] != workspaceVO.user.currentRole.roleId){
			Ccay.UI.showMessage("ccay.common.message.roleOrUserChanged","error");
			return ;
		}
	map = new Ccay.HashMap();
	Ccay.doGet("services/ccay/registry/query/list/{0}/{1}".formatURI("Ccay.Security.NoPermissionMsg",false),'',
		    function(data){
		    	//避免重复弹出 
				if(Ccay.Component.handleNoPermissionErorDialog){
					return;
				}
				for(var a=0;a<data.length;a++){
					map.put(data[a].name,data[a].value);
				}
				//配置是否启用优化后的无权限提示页面
				if(map.get("MessageType")==1){
					var noPermissionOpt = {
					width: 480,
					height: 185,
					cancelClick: true,
					fnLoad: function(){
						Ccay.security.noPermission.noPermissionMessage.init(permItems[1],permItems[2],permItems[3]);
					},fnClose:function(){ 
						Ccay.Component.handleNoPermissionErorDialog = null;
					}};
					Ccay.Page.register("Ccay.security.noPermission.noPermissionMessage","ccay/security/noPermission/noPermissionMessage.html");
					Ccay.Component.handleNoPermissionErorDialog=Ccay.UI.dialog("Ccay.security.noPermission.noPermissionMessage", "ccay.security.label.warmWarn", noPermissionOpt);
				}else {
					Ccay.UI.showMessage("ccay.common.message.noPrivilegeError", "error");
				}
		    }
	);
	} else {
		Ccay.UI.showMessage("ccay.common.message.roleOrUserChanged","error");
	}
	
	
};

/**
 * 处理验证错误
 * @param {} fault
 * @param {} fnCallback
 * @param {} callbackParameter
 */
Ccay.Component.handleValidationError=function(fault){
	// 服务器端验证的显示处理
			var validErrors = Ccay.DataHelper.toJson(fault.message);
			if( validErrors.actionErrors.length && validErrors.actionErrors.length > 0 ) {
				// action的验证处理
				var validMessage = "<div></div>";
				validMessage += validErrors.actionErrors.join("<br />");
				for(var i=0; i < validErrors.actionErrors.length; i++){
					validMessage.append("<ul>" + validErrors.actionErrors[i].encode() + "</ul>");
				}
				// 在form弹出tip
				var activeForm = Ccay.Core.getActiveForm();
				if ( typeof(theForm) === "undefined" ) {
					activeForm = Sigma.activeGrid;
				}
				activeForm.ccayTip(validMessage[0].outerHTML);
			}
			if(validErrors.fieldErrors){
				// 字段的验证处理
				for(var i=0; i < validErrors.fieldErrors.length; i++){
					var fieldName = validErrors.fieldErrors[i].fieldName.split(".").pop();
					
					var rowIndex = validErrors.fieldErrors[i].rowIndex;
					// 根据rowIndex，来区别为grid还是form
					if (rowIndex != -1) {
						// grid处理
						var activeGrid = Sigma.activeGrid;
						var col = activeGrid.getColumn(fieldName);
						var row = activeGrid.gridTable.rows.item(rowIndex);
						var cell = row.cells[col.getColumnIndex()];
						activeGrid.showValidResult("", validErrors.fieldErrors[i].messages, cell, col);
					} else {
						// form处理
						var message = validErrors.fieldErrors[i].messages.join("<br />");
						
						var activeForm = Ccay.Core.getActiveForm();
						var element = $("[name='" + fieldName + "']", activeForm);
						var label = $("<LABEL/>")
						.attr({"for":  element.attr("id"), generated: true})
						.addClass("error")
						.html(message || "");
						// 给对应的字段加上验证样式
						Ccay.UI.toggleValid(false, element, label, true);
					}
				}
			}
};
Ccay.Core.handleError = Ccay.Component.handleError;



